<template>
    <view class="container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <view class="left">
                <u-icon name="arrow-left" size="32" color="#333" @click="goBack"></u-icon>
            </view>
            <view class="title">聊天历史记录</view>
        </view>
        
        <!-- 历史记录列表 -->
        <scroll-view class="records-scroll" scroll-y @scrolltolower="loadMore">
            <view class="record-list">
                <view class="record-item" v-for="(item, index) in records" :key="index" @click="viewDetail(item.id)">
                    <view class="header">
                        <view class="time">{{item.time}}</view>
                        <view class="count">
                            <text class="label">消息数：</text>
                            <text class="value">{{item.messageCount}}</text>
                        </view>
                    </view>
                    
                    <view class="content">
                        <view class="summary">{{item.summary}}</view>
                    </view>
                    
                    <view class="footer">
                        <view class="status" :class="item.status">{{getStatusText(item.status)}}</view>
                        <u-icon name="arrow-right" size="24" color="#999"></u-icon>
                    </view>
                </view>
            </view>
            
            <!-- 加载更多 -->
            <view class="load-more" v-if="hasMore">
                <u-loadmore status="loading" />
            </view>
            
            <!-- 无数据 -->
            <view class="empty" v-if="records.length === 0">
                <image src="/static/images/empty.png" mode="aspectFit"></image>
                <text>暂无历史记录</text>
            </view>
        </scroll-view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            doctorId: '',
            records: [],
            page: 1,
            pageSize: 10,
            hasMore: true,
            loading: false
        }
    },
    methods: {
        goBack() {
            uni.navigateBack();
        },
        
        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                'ongoing': '进行中',
                'completed': '已完成',
                'canceled': '已取消'
            };
            return statusMap[status] || '未知';
        },
        
        // 加载聊天历史记录
        loadRecords() {
            if (this.loading || !this.hasMore) return;
            
            this.loading = true;
            
            try {
                // 从本地存储获取真实聊天记录，基于医生ID筛选
                const chatKey = `chat_history_${this.doctorId}`;
                const savedChat = uni.getStorageSync(chatKey);
                console.log('尝试加载聊天记录, key:', chatKey);
                
                if (savedChat) {
                    try {
                        const chatHistory = JSON.parse(savedChat);
                        if (Array.isArray(chatHistory) && chatHistory.length > 0) {
                            // 创建历史记录摘要
                            // 按日期分组聊天记录
                            const chatDates = {};
                            chatHistory.forEach(msg => {
                                const date = this.extractDateFromTime(msg.time);
                                if (!chatDates[date]) {
                                    chatDates[date] = {
                                        messages: [],
                                        count: 0
                                    };
                                }
                                chatDates[date].messages.push(msg);
                                chatDates[date].count++;
                            });
                            
                            // 将分组后的聊天记录转换为历史记录列表
                            const records = [];
                            Object.keys(chatDates).sort((a, b) => new Date(b) - new Date(a)).forEach(date => {
                                const chat = chatDates[date];
                                // 提取聊天摘要
                                let summary = '';
                                // 查找第一条有内容的消息
                                for (const msg of chat.messages) {
                                    if (msg.content && msg.type === 'text' && msg.content.length > 0) {
                                        summary = msg.content;
                                        if (summary.length > 30) {
                                            summary = summary.substring(0, 30) + '...';
                                        }
                                        break;
                                    }
                                }
                                
                                records.push({
                                    id: date.replace(/[^0-9]/g, ''), // 将日期作为ID
                                    time: date,
                                    messageCount: chat.count,
                                    summary: summary || '图片聊天记录',
                                    status: 'completed',
                                    messages: chat.messages
                                });
                            });
                            
                            this.records = records;
                            
                            console.log('已加载聊天历史记录', records.length, '条');
                            this.hasMore = false; // 本地存储中只有一组聊天记录
                        } else {
                            console.log('聊天记录为空或格式错误');
                            this.records = [];
                        }
                    } catch (e) {
                        console.error('解析聊天记录失败:', e);
                        this.records = [];
                    }
                } else {
                    console.log('未找到聊天记录');
                    this.records = [];
                }
                
                // 完成加载
                this.loading = false;
            } catch (error) {
                console.error('加载聊天记录错误:', error);
                this.loading = false;
                this.records = [];
                
                uni.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });
            }
        },
        
        // 从时间字符串中提取日期
        extractDateFromTime(timeString) {
            // 如果是YYYY-MM-DD HH:MM格式
            if (timeString.includes('-')) {
                return timeString.split(' ')[0]; // 提取日期部分
            }
            
            // 如果只有HH:MM格式（今天的消息）
            const today = new Date();
            return `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
        },
        
        // 加载更多
        loadMore() {
            if (!this.loading && this.hasMore) {
                this.loadRecords();
            }
        },
        
        // 查看详情
        viewDetail(id) {
            // 获取对应日期的消息记录
            const record = this.records.find(item => item.id === id);
            if (!record) {
                uni.showToast({
                    title: '记录不存在',
                    icon: 'none'
                });
                return;
            }
            
            // 处理跳转，将日期作为记录ID传递
            uni.navigateTo({
                url: `/pages/consultation/chat?id=${this.doctorId}&date=${record.time}`
            });
        }
    },
    onLoad(options) {
        if (options.doctorId) {
            this.doctorId = options.doctorId;
            this.loadRecords();
        } else {
            uni.showToast({
                title: '参数错误',
                icon: 'none'
            });
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        }
    }
}
</script>

<style lang="scss">
.container {
    min-height: 100vh;
    background-color: #F7F7FA;
    
    .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 30rpx;
        background-color: #fff;
        
        .title {
            font-size: 36rpx;
            font-weight: bold;
            color: #333;
        }
    }
    
    .records-scroll {
        height: calc(100vh - 100rpx);
        
        .record-list {
            padding: 20rpx;
            
            .record-item {
                background-color: #fff;
                border-radius: 20rpx;
                margin-bottom: 20rpx;
                padding: 30rpx;
                
                .header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 20rpx;
                    
                    .time {
                        font-size: 28rpx;
                        color: #333;
                        font-weight: bold;
                    }
                    
                    .count {
                        font-size: 24rpx;
                        color: #666;
                        
                        .value {
                            color: #1890FF;
                            font-weight: bold;
                        }
                    }
                }
                
                .content {
                    margin-bottom: 20rpx;
                    
                    .summary {
                        font-size: 28rpx;
                        color: #333;
                        line-height: 1.6;
                    }
                }
                
                .footer {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    
                    .status {
                        font-size: 24rpx;
                        padding: 6rpx 20rpx;
                        border-radius: 30rpx;
                        
                        &.ongoing {
                            color: #1890FF;
                            background-color: #E6F7FF;
                        }
                        
                        &.completed {
                            color: #52C41A;
                            background-color: #F6FFED;
                        }
                        
                        &.canceled {
                            color: #FF4D4F;
                            background-color: #FFF1F0;
                        }
                    }
                }
            }
        }
        
        .load-more {
            padding: 20rpx 0;
            text-align: center;
        }
        
        .empty {
            padding: 100rpx 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            
            image {
                width: 200rpx;
                height: 200rpx;
                margin-bottom: 20rpx;
            }
            
            text {
                font-size: 28rpx;
                color: #999;
            }
        }
    }
}
</style> 